import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

class Message {
    public String from;
    public String to;
    public String message;
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    // Jackson 里 核心的对象, 用来处理 json
    private ObjectMapper objectMapper = new ObjectMapper();

    // 消息列表
    // private List<Message> messages = new ArrayList<>();
    // 改成数据库就不需要这个变量了

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 将消息列表的内容, 全部返回给客户端
        // 也需要 ObjectMapper 将 message 对象, 转为 json 格式的字符串
        List<Message> messages = load();
        String jsonString = objectMapper.writeValueAsString(messages);
        System.out.println("jsonString" + jsonString);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(jsonString);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理提交消息的请求
        // 用 objectMapper 将 json格式的字符串 转为 message 对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        save(message);
        // 响应, body 是 json 格式的
        // 设置了json格式, jquery ajax 就会自动帮我们把字符串转为 js 对象
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write("{\"ok\": true}");
    }

    private void save(Message message) {
        // 把一条消息保存到数据库
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            // 1. 与数据库建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 SQL 语句
            String sql = "insert into message values(?, ?, ?)"; // ? 占位符
            statement = connection.prepareStatement(sql); // 预编译
            statement.setString(1, message.from);
            statement.setString(2, message.to);
            statement.setString(3, message.message);
            // 3. 执行 SQL
            statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 4. 释放资源
            DBUtil.close(connection, statement, null);
        }
    }

    private List<Message> load() {
        // 获取数据库中所有的消息
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Message> messages = new ArrayList<>();
        try {
            // 1. 建立连接
            connection = DBUtil.getConnection();
            // 2. 构造 SQL
            String sql = "select * from message";
            statement = connection.prepareStatement(sql);
            // 3. 执行 SQL
            resultSet = statement.executeQuery();
            // 4. 循环遍历结果集
            while (resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messages.add(message);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            DBUtil.close(connection, statement, resultSet);
        }
        // 6. 返回结果
        return messages;
    }
}
